<?php
/**
 * 全局控制文件
 *
 * @author virowin<virowin@gmail.com>
 * @version 1.0 2011-03-25
 */

//错误调试
ini_set("display_errors", $CFG['display_errors']);
error_reporting($CFG['error_level']);

//xhprof debug
if (isset($_REQUEST['xhprof_debug'])) {
    //如果加载了xhprof扩展 并且加载了xhprof文件
    if (in_array('xhprof',get_loaded_extensions()) && file_exists($CFG['xhprof_path']."/xhprof_lib/utils/xhprof_lib.php")) {
        ob_start();
        xhprof_enable(XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY);
        function xhprof_shutdown(){
            global $CFG;
            $xhprof_data = xhprof_disable();
            include_once $CFG['xhprof_path']."/xhprof_lib/utils/xhprof_lib.php";
            include_once $CFG['xhprof_path']."/xhprof_lib/utils/xhprof_runs.php";
            $xhprof_runs = new XHProfRuns_Default();
            $xhprof_runs->save_run($xhprof_data, 'xhprof');
            ob_flush();
        }
        register_shutdown_function('xhprof_shutdown');
    }
}

//临时加载soap模块. TODO::默认打开soap扩展
//if (!extension_loaded('soap')) {
//	dl('soap.'.PHP_SHLIB_SUFFIX);
//	ini_set('soap.wsdl_cache_enabled','0');
//	ini_set('soap.wsdl_cache_ttl',86400);
//	if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
//		ini_set('soap.wsdl_cache_dir',"C:\WINDOWS\Temp");
//	} else {
//		ini_set('soap.wsdl_cache_dir',"/tmp");
//	}
//}

//自定义输出错误堆栈,如果不想要trace_debug,那么在报错页面,加入 restore_error_handler();
function trace_debug(){
    $files = get_included_files();
    echo "<pre>";
    debug_print_backtrace();
    var_dump($files);
    echo "</pre>";
}
if ($CFG['display_errors'] || isset($_GET['zhouwei_debug'])) {
    set_error_handler('trace_debug',E_ALL^E_NOTICE);
}

//时区设置
date_default_timezone_set('Asia/Shanghai');

function env_info(){
    global $CFG;
    global $user_info;
    global $Template;
    global $ERROR_DESC;
    $debug_time_use = microtime(true)-$CFG['time_start'];
    $include_files = get_included_files();
    $extensions = get_loaded_extensions();

    output_env_info('memory_get_usage',memory_get_usage(1));
    output_env_info('debug_time_use',$debug_time_use);
    output_env_info('CFG',$CFG);
    output_env_info('ERROR_DESC',$ERROR_DESC);
    output_env_info('user_info',$user_info);
    output_env_info('include_files',$include_files);
    output_env_info('extensions',$extensions);
    output_env_info('error',error_get_last());
    output_env_info('Template',$Template);
}
function output_env_info($key,$value){
    $id = substr(md5(time().rand(0,10000)),0,20);
    echo '<span style="cursor:pointer; font-size: 24px; color: #F00;" onclick="document.getElementById(\''.$id.'\').style.display=(document.getElementById(\''.$id.'\').style.display == \'block\')?\'none\':\'block\';">';
    echo $key."</span><br/>";
    echo "<div id=\"".$id."\" style=\"display:none;\"><pre>";
    var_dump($value);
    echo "</pre></div>";
}
if (isset($_GET['zhouwei_debug'])) {
    register_shutdown_function('env_info');
}

if (isset($_REQUEST['nocache'])) {
    $CFG['use_cache'] = false;
}

//cache the Fatal error and the Warning
//注意 此warning非彼Warning 详见:http://www.php.net/manual/en/errorfunc.constants.php
function shutdown_error_log(){
    $error = error_get_last();
    if (in_array($error['type'],array(E_ERROR,E_WARNING))) {
        $log_arr = array(
        'url'=>get_page_url(),
        'error'=>$error,
        );
        Lib_Logger::log_error(serialize($log_arr));
    }
}
register_shutdown_function('shutdown_error_log');

####################################################
#全局变量初始化
####################################################
$MDD = array();
$user_info = array();
$Template = array();

//输入数据处理
function process_get_post() {
    $clean_gp = array();
    //Add slash
    if (!get_magic_quotes_gpc ()) {
        $_GET = deep_add_slashes( $_GET );
        $_POST = deep_add_slashes( $_POST );
    }
    //trim each value and assign to one array.
    foreach( array_merge( $_POST, $_GET ) as $k => $v ) {
        $clean_gp[$k] = is_array($v) ? $v : trim( $v );
    }
    return $clean_gp;
}
//为输入参数添加slash
function deep_add_slashes( $var ) {
    if( is_array( $var ) ) {
        foreach( $var as $key => $val ) {
            $var[$key] = deep_add_slashes( $val );
        }
    } else {
        $var = addslashes( $var );
    }
    return $var;
}
$clean_gp = process_get_post();


/**
 * 类自动加载
 *
 */
function becca_autoload($className)
{
    global $CFG;
    static $_classes = array() ;
    if (class_exists($className, false) || interface_exists($className, false)){
        return;
    }elseif(isset($_classes[$className])){
        include "{$_classes[$className]}" ;
    }else{
        //先走一遍LIB目录
        $file = $CFG['lib_path'].'/'.str_replace('_', '/', str_replace('Lib_', '', $className)) . '.php';
        if (file_exists("{$file}")) {
            $_classes[$className] = $file ;
            include "{$file}" ;
        }else{
            //不行再走class
            $file = $CFG['class_path'].'/'.str_replace('_', '/', $className) . '.php';
            if (file_exists("{$file}")) {
                $_classes[$className] = $file ;
                include "{$file}" ;
            }
        }
    }
}
spl_autoload_register('becca_autoload');

/**
 * 加载相关配置及全局函数文件
 *
 */
//常量
require_once $CFG['include_path'] . '/constants.php';

//全局方法
require_once $CFG['include_path'] . '/function.php';

//系统路由 需要设置 $CFG['system_router']=1 ; $CFG['router_class_prefix'] = 'Testrouter_Biz_';
/** #nginx 需要配置
        rewrite (.*\.(js|css|ico|gif|jpg|jpeg|png|html))$ /$1 break;
        if ($request_filename !~* /(index\.php|static|html|images|uploads|poster|manageadmin|issue|vcode|yuan-phpinfo\.php|robots\.txt)) {
                rewrite ^/(.*)$ /index.php?$1 last;
        }
   #项目需要配置
   //router example
	$CFG['system_router'] = 1;
	$CFG['router_class_prefix'] = 'Complaints_App_';
	$CFG['router_default_class'] = 'Area';
	$CFG['router_default_function'] = 'index';
	$CFG['router_default_param'] = array();
 */
if ($CFG['system_router']) {
    require_once $CFG['include_path'] . '/router.php';
    try {
        $Router = new Router();
        $Router->routing();
    }catch (Exception $e){
        if (isset($_REQUEST['zhouwei_debug'])) {
            echo '<pre>';
            var_dump($e);
            echo '</pre>';
            debug_print_backtrace();
        }else{
            header('HTTP/1.1 404 Not Found');exit;
        }
    }
}

//only for test
if ($CFG['system_router2']) {
    require_once $CFG['include_path'] . '/router2.php';
    try {
        $Router = new Router();
        $Router->routing();
    }catch (Exception $e){
        if (isset($_REQUEST['zhouwei_debug'])) {
            echo '<pre>';
            var_dump($e);
            echo '</pre>';
            debug_print_backtrace();
        }else{
            header('HTTP/1.1 404 Not Found');exit;
        }
    }
}


#挡板开关...(必须先配置了app_name)
//$errorCode = 1;
//ErrorExit($errorCode,$ERROR_DESC[$errorCode],$CFG['app_name']);
